package com.gitee.neuray.security.mail.util;

import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @auther: zhuqz
 * @date: 2020/2/26 09:41
 * @description:
 */
public class EmailCommon {
    //文件转换二进制流
    public static byte[] fileToBytes(File file){
        byte[] data = null;
        try{
            FileInputStream fim = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fim.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            data = bos.toByteArray();
            fim.close();
            bos.close();
        }catch (Exception e){
            System.out.println("转换报错");
            e.printStackTrace();
        }
        return data;
    }
    //文件转换二进制流
    public static byte[] fileToBytes(InputStream im){
        byte[] data = null;
        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = im.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            data = bos.toByteArray();
            im.close();
            bos.close();
        }catch (Exception e){
            System.out.println("转换报错");
            e.printStackTrace();
        }
        return data;
    }
    //二进制流base64转码
    public static String  bytesEncodeBase64 (byte[] datas){
        BASE64Encoder encoder = new BASE64Encoder();
        return datas != null ? encoder.encode(datas) : "";
    }
    //文件转二进制转base64
    public static String fileToBytesToBase64(File file){
        return  bytesEncodeBase64(fileToBytes(file));
    }
    //文件转二进制转base64
    public static String fileToBytesToBase64(InputStream im){
        return  bytesEncodeBase64(fileToBytes(im));
    }

}